﻿/*
COPYRIGHT (C) 2009 EPISERVER AB

THIS FILE IS PART OF MAPPED PAGE PROVIDER FOR EPISERVER CMS.
MAPPED PAGE PROVIDER FOR EPISERVER CMS IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

MAPPED PAGE PROVIDER FOR EPISERVER CMS IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER GENERAL PUBLIC LICENSE FOR MORE DETAILS.
YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH MAPPED PAGE PROVIDER FOR EPISERVER CMS. IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EPiServer.DataAccess;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Runtime.CompilerServices;

namespace EPiServer.Research.PageProviders
{
    public class MappedPPDB : DataAccessBase
    {
        private static MappedPPDB _instance;

        public static MappedPPDB Instance
        {
            get
            {
                if (_instance == null) _instance = new MappedPPDB();
                return _instance;
            }
        }

        private Dictionary<string, PageProviderCache> _cachedMappings;

        protected PageProviderMapping GetFromCache(string Provider, string Key)
        {
            if (!_cachedMappings.ContainsKey(Provider)) return null;
            return _cachedMappings[Provider].GetFromCache(Key);
        }

        protected PageProviderMapping GetFromCache(string Provider, int ID)
        {
            if (!_cachedMappings.ContainsKey(Provider)) return null;
            return _cachedMappings[Provider].GetFromCache(ID);

        }

        protected PageProviderMapping GetFromCache(string Provider, Guid g)
        {
            if (!_cachedMappings.ContainsKey(Provider)) return null;
            return _cachedMappings[Provider].GetFromCache(g);
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        protected void AddToCache(string Provider, PageProviderMapping pm)
        {
            if (!_cachedMappings.ContainsKey(Provider)) _cachedMappings.Add(Provider, new PageProviderCache());

            _cachedMappings[Provider].AddToCache(pm);
        }

        public MappedPPDB()
        {
            CreateIfNotExist();
            _cachedMappings = new Dictionary<string, PageProviderCache>();
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        protected PageProviderMapping LoadMapping(string ProviderName, string Clause, object param)
        {

            PageProviderMapping ppm = base.Execute<PageProviderMapping>(delegate
            {

                PageProviderMapping rt = null;
                string get = "SELECT PageKey, PageID, PageGuid FROM tblPageProviderMappings WHERE ProviderID=@ProviderName AND " + Clause + "=@Param";
                IDbCommand cmd = base.CreateTextCommand(get);
                cmd.Parameters.Add(base.CreateParameter("ProviderName", ProviderName));
                cmd.Parameters.Add(base.CreateParameter("Param", param));

                IDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleResult);
                if (reader.Read())
                {
                    rt = new PageProviderMapping();
                    rt.Key = (string)reader["PageKey"];
                    rt.ID = (int)reader["PageID"];
                    rt.Guid = (Guid)reader["PageGuid"];
                }
                return rt;
            });



            if ((ppm == null) && (Clause == "PageKey"))
            {
                return AddKey(ProviderName, (string)param);
            }
            return ppm;
        }


        public void RemoveId(string ProviderName, int Id)
        {
            string k = LoadMapping(ProviderName, Id).Key;
            DeleteMapping(ProviderName, k);
        }

        public PageProviderMapping AddKey(string ProviderName, string Key)
        {
            PageProviderMapping ppm = new PageProviderMapping();
            ppm.Key = Key;
            ppm.Guid = Guid.NewGuid();
            int maxId = base.Execute<int>(delegate
            {
                IDbCommand cmd = base.CreateTextCommand("SELECT MAX(PageID) FROM tblPageProviderMappings WHERE ProviderID=@Provider");
                cmd.Parameters.Add(base.CreateParameter("Provider", ProviderName));
                object o = cmd.ExecuteScalar();
                int maxID = 0;
                if (o != null && o != DBNull.Value) maxID = (int)o;
                return maxID;
            });
            ppm.ID = maxId + 1;

            base.Execute(delegate
            {
                IDbCommand cmd2 = base.CreateTextCommand("INSERT INTO tblPageProviderMappings (ProviderID,PageKey,PageID,PageGuid) VALUES (@ProviderID,@PageKey,@PageID, @PageGuid)");
                cmd2.Parameters.Add(base.CreateParameter("ProviderID", ProviderName));
                cmd2.Parameters.Add(base.CreateParameter("PageKey", ppm.Key));
                cmd2.Parameters.Add(base.CreateParameter("PageID", ppm.ID));
                cmd2.Parameters.Add(base.CreateParameter("PageGuid", ppm.Guid));
                cmd2.ExecuteNonQuery();
            });
            return ppm;
        }

        public PageProviderMapping LoadMapping(string ProviderName, Guid g)
        {
            PageProviderMapping pm = GetFromCache(ProviderName, g);
            if (pm != null) return pm;
            pm = LoadMapping(ProviderName, "PageGuid", g);
            if (pm != null) AddToCache(ProviderName, pm);
            return pm;
        }

        public PageProviderMapping LoadMapping(string ProviderName, int id)
        {
            PageProviderMapping pm = GetFromCache(ProviderName, id);
            if (pm != null) return pm;
            pm = LoadMapping(ProviderName, "PageID", id);
            if (pm != null) AddToCache(ProviderName, pm);
            return pm;
        }

        public PageProviderMapping LoadMapping(string ProviderName, string Key)
        {
            PageProviderMapping pm = GetFromCache(ProviderName, Key);
            if (pm != null) return pm;
            pm = LoadMapping(ProviderName, "PageKey", Key);
            if (pm != null) AddToCache(ProviderName, pm);
            return pm;
        }

        public void DeleteMapping(string ProviderName, string Key)
        {
            //TODO: Remove from cache
            base.Execute(delegate
            {
                IDbCommand cmd = base.CreateTextCommand("DELETE FROM tblPageProviderMappings WHERE ProviderID=@Provider AND PageKey=@Key");
                cmd.Parameters.Add(base.CreateTextParameter("Provider", ProviderName));
                cmd.Parameters.Add(base.CreateTextParameter("Key", Key));
                cmd.ExecuteNonQuery();
            });
        }

        protected void CreateIfNotExist()
        {
            bool exist = base.Execute<bool>(delegate
            {
                IDbCommand cmd = base.CreateCommand("select count(name) from sysobjects where xtype='u' and name = 'tblPageProviderMappings'");
                cmd.CommandType = CommandType.Text;
                int v = (int)cmd.ExecuteScalar();
                return (v == 1);
            });

            if (!exist)
            {
                base.Execute(delegate
                {
                    string create = "CREATE TABLE [dbo].[tblPageProviderMappings](" +
                                "[ProviderID] [nchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL," +
                                "	[PageKey] [nvarchar](256) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL," +
                                "	[PageID] [int] NOT NULL," +
                                "	[PageGuid] [uniqueidentifier] NOT NULL," +
                                " CONSTRAINT [PK_tblPageProviderMappings] PRIMARY KEY CLUSTERED " +
                                "(" +
                                "	[ProviderID] ASC," +
                                "	[PageKey] ASC" +
                                ")WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]" +
                                ") ON [PRIMARY]";
                    IDbCommand cmd = base.CreateTextCommand(create);
                    cmd.ExecuteNonQuery();
                });
            }


        }
    }
}
